package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.entity.UserInfo;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller
public class GiteeBindController {


    @Autowired
    UserMapper userMapper;

    @RequestMapping("/callbackCode.do")
    public String callbackCode(String code, HttpServletRequest request,HttpServletResponse response,Model model) {
        System.out.println("接收到的临时授权码 " + code);

        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token " + tokenByCode);

        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);
        System.out.println("获取到的用户信息" + JSON.toJSONString(userInfoByToken));

        // 绑定需要获取 三个字段  昵称  头像  giteeId

        String nickName = userInfoByToken.getString("name");
        String avatarUrl = userInfoByToken.getString("avatar_url");
        Integer giteeId = userInfoByToken.getInteger("id");

        // 获取当前登录的用户  从cookie中拿到token  再解密token
        UserInfo userFromRequest = TokenUtils.getLoginUserFromRequest(request, UserInfo.class);

        // 合并这个两个账号信息

        userFromRequest.setGiteeId(giteeId);
        userFromRequest.setAvatarUrl(avatarUrl);
        userFromRequest.setNickName(nickName);
        userMapper.updateUserById(userFromRequest);

        // 重新制作token

        TokenUtils.responseTokenByCookie(userFromRequest,response);

        model.addAttribute("nickName",nickName);
        model.addAttribute("avatarUrl",avatarUrl);
        return "success";
    }




}
